package com.zry.pda.presenter

import android.app.AlertDialog
import android.content.Intent
import android.util.Log
import android.view.View

import com.zry.pda.R
import com.zry.pda.retrofit.BaseApiRetrofit
import com.zry.pda.retrofit.ShowUserView

import com.zry.pda.ui.activity.LoginActivity
import com.zry.pda.ui.activity.MoreOperateActivity
import com.zry.pda.update.PackageInfoUtil
import com.zry.pda.update.UpdateAppInfo
import com.zry.pda.update.UpdateAppService
import com.zry.pda.utils.SpUtil
import com.zry.pda.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_more_operate.*


class MoreOperatePresenter(private var activity: MoreOperateActivity) : ShowUserView {

    fun moreOperateClick(view: View) {
        when (view.id) {
            R.id.versionUpdateRelative -> {
                updateApp()
            }
            R.id.cancellationText -> {
                SpUtil().clearData(activity)
                val intent = Intent(activity, LoginActivity::class.java)
                activity.startActivity(intent)
            }
        }
    }


    private var updateAppInfo: UpdateAppInfo? = null

    fun checkApp(vNumber: String) {
        Log.e("vNumber", vNumber)
        HttpServer(this).checkApp(vNumber, activity)
    }

    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            26 -> {
                updateAppInfo = data as UpdateAppInfo
                if (updateAppInfo?.state==1){
                    activity.versionUpdateImg.visibility=View.VISIBLE
                }
            }
        }
    }

    private fun updateApp() {
        //版本更新
        //获取当前app的版本号
        Log.e("VersionCode", PackageInfoUtil.getVersionCode(activity).toString())

        if (updateAppInfo!!.state == 1) {
            val mDialog: AlertDialog.Builder = AlertDialog.Builder(activity)
            mDialog.setTitle(BaseApiRetrofit.APK_NAME + "又更新咯！")
            mDialog.setPositiveButton("立即更新") { _, _ ->
                val intent = Intent(activity, UpdateAppService::class.java)
                activity.startService(intent)
            }?.setNegativeButton("暂不更新") { dialog, which -> dialog.dismiss() }?.setCancelable(false)?.create()?.show()
        } else {
            ToastUtil.toast(activity, "暂时没有检测到新版本")
        }
    }


}